package io.renren.modules.file.controller;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import io.renren.common.validator.ValidatorUtils;
import io.renren.modules.file.entity.OperLogEntity;
import io.renren.modules.file.entity.ServerNodeEntity;
import io.renren.modules.file.service.OperLogService;
import io.renren.modules.file.service.ServerNodeService;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import io.renren.modules.file.entity.FileEntity;
import io.renren.modules.file.service.FileService;
import io.renren.common.utils.R;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 文件管理
 *
 * @author cheng
 * @email 751018031@qq.com
 * @date 2019-06-13 16:19:05
 */
//@RestController
@Controller
@RequestMapping("file/file")
public class FileController {
    @Autowired
    private FileService fileService;

    @Autowired
    ServerNodeService serverNodeService;

    @Autowired
    OperLogService operLogService;

    //分隔符
    private final String SPRIT = "/";
    //操作类型
    private final String PER_TYPE_UP = "下载";
    private final String PER_TYPE_DE = "删除";
    /**
     * 循环遍历文件集合
     *
     * @param file
     * @param level
     * @param parentFile
     */
    public void listF(File file, int level, FileEntity parentFile) {
        //得到物理路径
        String pach = file.getPath().replace("\\","%2F");
        String str = "";
        for (int i = 0; i < level; i++) {
            str += "    ";
        }
        parentFile.setName(file.getName());
//        System.out.println(str + file.getName());
        parentFile.setUrl("/file/file/downloadFolder?path=" + pach);
        parentFile.setTarget("_self");
        parentFile.setOpen(true);
        //得到file的所有文件和文件夹
        File[] f = file.listFiles();
        if (f != null && f.length > 0) {
            List<FileEntity> fileEntities = new ArrayList<>();
            for (File f1 : f) {
                FileEntity childFile = new FileEntity();
                childFile.setParentT(parentFile);
                childFile.setName(f1.getName());
                fileEntities.add(childFile);
                listF(f1, level + 1, childFile);
            }
            parentFile.setChildren(fileEntities);
        }
    }

    /**
     * 列表
     */
    @ResponseBody
    @RequestMapping("/list")
    @RequiresPermissions("file:file:list")
    public R list(String pach,@RequestParam Map<String, Object> params) {
        List<ServerNodeEntity> serverNodeEntities = serverNodeService.list();
        //得到文件目录
//        FTPUtil ftpUtil = new FTPUtil();
//        ftpUtil.setFtp_address("192.168.10.91");
        //得到文件树
        File file = new File("D:\\ftpDown");
        FileEntity fileEntity = new FileEntity();
        fileEntity.setName("ftpDown");
        listF(file, 1, fileEntity);
        //子节点关闭
        if (fileEntity.getChildren()!= null) {
            for (FileEntity fileEntity1 : fileEntity.getChildren()) {
                fileEntity1.setOpen(false);
            }
        }
        //得到树形菜单
//        PageUtils page = fileService.queryPage(params);
        return R.ok().put("data", fileEntity);
    }

    /**
     * 删除磁盘文件
     */
    @RequestMapping("/deleteFile")
    public R deleteFile(String path) {
        File file = new File(path);
        if (file.delete()) {
            OperLogEntity operLogEntity = new OperLogEntity();
            operLogEntity.setOperUserId(ShiroUtils.getUserId());
            operLogEntity.setOperUserName(ShiroUtils.getUserEntity().getUsername());
            operLogEntity.setCreatTime(new Date());
            operLogEntity.setType(PER_TYPE_DE);
            operLogService.save(operLogEntity);
            return R.ok("文件删除成功");
        } else {
            return R.error("文件删除失败");
        }
    }

    /**
     * 文件夹打包下载
     */
    @RequestMapping("/downloadFolder")
    public void downloadFolder(String path, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] arrys = path.split("/");
        String fileName = arrys[arrys.length - 1];
        // 请求客户端操作系统的信息
        final String userAgent = request.getHeader("USER-AGENT");
        //文件名
        if (userAgent.contains("Firefox")) {
            //是火狐浏览器，使用BASE64编码
            fileName = "=?utf-8?b?" + new BASE64Encoder().encode(fileName.getBytes("utf-8")) + "?=";
        } else {
            //给文件名进行URL编码
            //URLEncoder.encode()需要两个参数，第一个参数时要编码的字符串，第二个是编码所采用的字符集
            fileName = URLEncoder.encode(fileName, "utf-8");
        }
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename="+fileName+".zip");
//            response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        //添加到zip
        ZipUtils.toZip(path, response.getOutputStream(), true);
        //添加操作日志
        OperLogEntity operLogEntity = new OperLogEntity();
        operLogEntity.setFileName(path);
        operLogEntity.setOperUserId(ShiroUtils.getUserId());
        operLogEntity.setOperUserName(ShiroUtils.getUserEntity().getUsername());
        operLogEntity.setCreatTime(new Date());
        operLogEntity.setType(PER_TYPE_UP);
        operLogService.save(operLogEntity);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("file:file:info")
    public R info(@PathVariable("id") Long id) {
        FileEntity file = fileService.getById(id);
        return R.ok().put("file", file);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("file:file:save")
    public R save(@RequestBody FileEntity file) {
        fileService.save(file);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("file:file:update")
    public R update(@RequestBody FileEntity file) {
        ValidatorUtils.validateEntity(file);
        fileService.updateById(file);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("file:file:delete")
    public R delete(@RequestBody Long[] ids) {
        fileService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    public static void main(String[] args) {
        File file=new File("D:\\ftpDown\\节点C\\秦时明月\\农家\\田咪.jpg");
        System.out.println(file.getName());
        System.out.println(file.delete());
    }

    //删除文件夹
//param folderPath 文件夹完整绝对路径

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除指定文件夹下所有文件
     //param path 文件夹完整绝对路径
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

}
